import React, { useState, useEffect } from "react";
import { Table, Button, Card, Divider, Pagination, Modal, message, Popconfirm } from "antd";
import {
  goodsAdd,
  goodsUpdate,
  goodsDel,
  goodsPage
} from "@/api/goods";
import {
  categoryPage
} from "@/api/category";
import AddForm from "./addForm";
import "./index.less";

function Goods() {
  const [goodsList, setGoodsList] = useState([])
  const [loading, setLoading] = useState(false)
  const [total, setTotal] = useState(0)
  const [pageNo, setPageNo] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [goodsInfo, setGoodsInfo] = useState({})
  const [_id, set_Id] = useState('')
  const [categories, setCategories] = useState([])
  const [tablesHeight, setTablesHeight] = useState(505)

  const columns = [
    {
      title: "名称",
      dataIndex: "name",
      key: "name",
      width: 120
    },
    {
      title: "图片",
      dataIndex: "img",
      key: "img",
      width: 150,
      render: (value, row, index) => {
        return (
          <img src={row.img} alt="" style={{ width: '100px', height: '80px' }}/>
        );
      }
    },
    {
      title: "分类",
      dataIndex: "typename",
      key: "typename",
      width: 120
    },
    {
      title: "价格",
      dataIndex: "price",
      key: "price",
      width: 120,
      render: (value, row, index) => {
        return (
          <span>¥ {row.price}</span>
        );
      }
    },
    {
      title: "描述",
      dataIndex: "desc",
      key: "desc"
    },
    {
      title: "创建时间",
      dataIndex: "created",
      key: "created",
      width: 170,
      responsive: ["md"]
    },
    {
      title: "修改时间",
      dataIndex: "updated",
      key: "updated",
      width: 170,
      responsive: ["md"]
    },
    {
      title: "操作",
      dataIndex: "Operation",
      key: "Operation",
      width: 150,
      // responsive: ["lg"],
      render: (value, row, index) => {
        return (
          <div>
            <Button
              type='primary'
              size='small'
              onClick={() => addFrom(row)}
            >
              修改
            </Button>
            <Divider type='vertical' />
            <Popconfirm
              title="您确定要删除此项吗？"
              okText="是"
              cancelText="否"
              onConfirm={() => delBtn(row._id)}
            >
              <Button
                type='primary'
                size='small'
                danger>
                删除
              </Button>
            </Popconfirm>
          </div>
        );
      }
    }
  ];

  const getGoodsList = () => {
    setLoading(true)
    goodsPage({ pageNo, pageSize })
      .then(res => {
        setGoodsList(res.data.data)
        setTotal(res.data.total)
        setLoading(false)
      })
      .catch(err => {
        setLoading(false)
      });
  };

  const getCategoriesList = () => {
    categoryPage({ pageNo: 1, pageSize: 999 })
      .then(res => {
        setCategories(res.data.data)
      })
      .catch(err => {
        setCategories([])
      });
  };

  const paginationChange = (pageNo, pageSize) => {
    setPageNo(pageNo)
    setPageSize(pageSize)
    getGoodsList()
  };

  const addFrom = row => {
    if (row) {
      // 编辑
      set_Id(row._id)
      setGoodsInfo(row)
      setIsModalVisible(true)
    } else {
      // 新增
      set_Id('')
      setGoodsInfo({})
      setIsModalVisible(true)
    }
  };

  const handleCancel = () => {
    set_Id('')
    setGoodsInfo({})
    setIsModalVisible(false)
  };

  useEffect(() => {
    getCategoriesList();
    getGoodsList();
    setTablesHeightM();
    window.onresize = () => {
      setTablesHeightM();
    }
  }, [])// eslint-disable-line react-hooks/exhaustive-deps

  // 计算表格高度
  const setTablesHeightM = () => {
    let aH = 0
    let oA = document.getElementById('root')
    let oH = oA.clientHeight || oA.offsetHeight
    aH = oH - 414
    setTablesHeight(aH)
  }

  const onOk = val => {
    if (_id) {
      goodsUpdate({ _id: _id, ...val }).then(res => {
        if (res.data.code === 200) {
          getGoodsList();
          message.success("修改成功");
        } else {
          message.error(res.data.msg);
        }
      });
    } else {
      goodsAdd({ ...val }).then(res => {
        if (res.data.code === 200) {
          getGoodsList();
          message.success("添加成功");
        } else {
          message.error(res.data.msg);
        }
      });
    }
    handleCancel()
  };

  const delBtn = _id => {
    goodsDel({ _id })
      .then(res => {
        if (res.data.code === 200) {
          getGoodsList()
          return message.success("删除成功")
        }
        message.error(res.data.msg)
      })
  }

  const title = "商品分类列表";
  const extra = <Button onClick={addFrom}>添加</Button>;

  return (
    <Card title={title} extra={extra} className="cardBox">
      <Table
        className="tableBox"
        rowKey='_id'
        loading={loading}
        columns={columns}
        dataSource={goodsList}
        pagination={false}
        scroll={{ y: tablesHeight }}
      />
      <br />
      {total ? (
        <Pagination
          total={total}
          showSizeChanger
          showQuickJumper
          showTotal={total => `共 ${total} 条`}
          onChange={paginationChange}
        />
      ) : (
        ""
      )}
      <Modal
        title='添加商品分类'
        visible={isModalVisible}
        onCancel={handleCancel}
        footer={null}
      >
        <AddForm
          onOk={onOk}
          onCancel={handleCancel}
          goodsInfo={goodsInfo}
          categories={categories}
        />
      </Modal>
    </Card>
  );
}

export default Goods;
